package com.jaws.demo.common.sharding.algorithm;


import com.jaws.core.common.log.Log;
import com.jaws.demo.common.enums.TableNameEnum;
import com.jaws.demo.common.sharding.util.TableSegmentUtils;
import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;

/**
 * account_trade 分表策略实现
 *
 * @author liangqm
 * @date 2018-05-03 9:36:18
 * @since v1.0.0
 */
@Slf4j
public class AccountTradeTableShardingAlgorithm implements PreciseShardingAlgorithm {

	@Override
	public String doSharding(Collection availableTargetNames, PreciseShardingValue shardingValue) {

		log.info(Log.op("AccountTradeTableShardingAlgorithm.doSharding").kv("availableTargetNames", availableTargetNames).kv("shardingValue", shardingValue).toString());

		// 分表编号
		String tableSegment = TableSegmentUtils.getTableSegment(TableNameEnum.ACCOUNT_TRADE, (String) shardingValue.getValue());

		// 真实表名称
		String actualTable = shardingValue.getLogicTableName() + tableSegment;

		// 验证表明是否存在在可用表明中
		if (availableTargetNames.contains(actualTable)) {
			return actualTable;
		}

		log.warn(Log.op("AccountTradeTableShardingAlgorithm.doSharding").kv("shardingValue",shardingValue).kv("actualTable",actualTable).msg("计算后的表名不在可用列表中").toString());

		// 计算出的真实表名 不在可用列表中，取可用列表第一个表名返回
		return (String) availableTargetNames.iterator().next();
	}


}

